/**
 * Copyright 2020 OPSLI 快速开发平台 https://www.opsli.com
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package org.opsli.modulars.shop.device.web;

import java.util.Date;
import java.util.List;
import java.util.Optional;
import cn.hutool.core.convert.Convert;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.opsli.api.base.result.ResultWrapper;
import org.opsli.api.web.shop.userorder.SysUserOrderRestApi;
import org.opsli.api.wrapper.shop.userorder.SysUserOrderModel;
import org.opsli.common.annotation.ApiRestController;
import org.opsli.core.base.controller.BaseRestController;
import org.opsli.core.persistence.Page;
import org.opsli.core.persistence.querybuilder.QueryBuilder;
import org.opsli.core.persistence.querybuilder.WebQueryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.opsli.core.log.enums.*;
import org.opsli.core.log.annotation.OperateLogger;

import org.opsli.modulars.shop.device.entity.SysShopDevice;
import org.opsli.api.wrapper.shop.device.SysShopDeviceModel;
import org.opsli.modulars.shop.device.service.ISysShopDeviceService;
import org.opsli.api.web.shop.device.SysShopDeviceRestApi;

/**
 * 门店设备 Controller
 *
 * @author 17607080935
 * @date 2025-01-08 17:12:50
 */
@Api(tags = SysShopDeviceRestApi.TITLE)
@Slf4j
@ApiRestController("/{ver}/shop/device")
public class SysShopDeviceRestController extends BaseRestController<SysShopDevice, SysShopDeviceModel, ISysShopDeviceService>
    implements SysShopDeviceRestApi {


    /**
     * 门店设备 查一条
     * @param model 模型
     * @return ResultWrapper
     */
    @ApiOperation(value = "获得单条门店设备", notes = "获得单条门店设备 - ID")
//    @PreAuthorize("hasAuthority('shop_device_select')")
    @Override
    public ResultWrapper<SysShopDeviceModel> get(SysShopDeviceModel model) {
        // 如果系统内部调用 则直接查数据库
        if(model != null && model.getIzApi() != null && model.getIzApi()){
            model = IService.get(model);
        }
        return ResultWrapper.getSuccessResultWrapper(model);
    }

    /**
     * 关闭设备
     * @param id
     */
    @Override
    public void closeDevice(String id) {
        try {
            Thread.sleep(2000); // 暂停 3 秒
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        log.info("设备已关闭");
    }





    /**
     * 开启设备
     */
    @Override
    @ApiOperation(value = "开启某个设备", notes = "开启某个设备")
    public ResultWrapper<?> openDoor(String type ,String id) {

        //开门

        //开房间门。订单开始消费
        if ("2".equals(type)){
            sysUserOrderRestApi.startOrder(id);
        }


        try {
            Thread.sleep(2000); // 暂停 3 秒
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        return ResultWrapper.getSuccessResultWrapper();
    }

    /**
     * 门店设备 查询分页
     * @param pageNo 当前页
     * @param pageSize 每页条数
     * @param request request
     * @return ResultWrapper
     */
    @ApiOperation(value = "根据日期门店id获取设备列表", notes = "根据日期门店id获取设备列表")
    @Override
    public ResultWrapper<?> findPageWeChat(String orgIds, Date date, Integer pageNo, Integer pageSize, HttpServletRequest request) {

        List<SysShopDeviceModel> list = IService.findPageWeChat(orgIds,date,pageNo,pageSize);
        for (SysShopDeviceModel sysShopDeviceModel : list) {
            List<SysUserOrderModel> orderModelList = sysUserOrderRestApi.getListByDate(date,sysShopDeviceModel.getOrgIds(), sysShopDeviceModel.getId());
            sysShopDeviceModel= IService.assembleShopDeviceOrder(sysShopDeviceModel, orderModelList);
        }
        return ResultWrapper.getSuccessResultWrapper(list);
    }

@Autowired
    SysUserOrderRestApi sysUserOrderRestApi;
    /**
     * 门店设备 查询分页
     * @param pageNo 当前页
     * @param pageSize 每页条数
     * @param request request
     * @return ResultWrapper
     */
    @ApiOperation(value = "获得分页数据", notes = "获得分页数据 - 查询构造器")
    @PreAuthorize("hasAuthority('shop_device_select')")
    @Override
    public ResultWrapper<?> findPage(Integer pageNo, Integer pageSize, HttpServletRequest request) {

        QueryBuilder<SysShopDevice> queryBuilder = new WebQueryBuilder<>(IService.getEntityClass(), request.getParameterMap());
        Page<SysShopDevice, SysShopDeviceModel> page = new Page<>(pageNo, pageSize);
        page.setQueryWrapper(queryBuilder.build());
        page = IService.findPage(page);

        return ResultWrapper.getSuccessResultWrapper(page.getPageData());
    }

    /**
     * 门店设备 新增
     * @param model 模型
     * @return ResultWrapper
     */
    @ApiOperation(value = "新增门店设备数据", notes = "新增门店设备数据")
    @PreAuthorize("hasAuthority('shop_device_insert')")
    @OperateLogger(description = "新增门店设备数据",
            module = ModuleEnum.MODULE_UNKNOWN, operationType = OperationTypeEnum.INSERT, db = true)
    @Override
    public ResultWrapper<?> insert(SysShopDeviceModel model) {
        // 调用新增方法

        model.setOrgIds(null);
        model = IService.insert(model);
        return ResultWrapper.getSuccessResultWrapperByMsg("新增门店设备成功");
    }

    /**
     * 门店设备 修改
     * @param model 模型
     * @return ResultWrapper
     */
    @ApiOperation(value = "修改门店设备数据", notes = "修改门店设备数据")
    @PreAuthorize("hasAuthority('shop_device_update')")
    @OperateLogger(description = "修改门店设备数据",
            module = ModuleEnum.MODULE_UNKNOWN, operationType = OperationTypeEnum.UPDATE, db = true)
    @Override
    public ResultWrapper<?> update(SysShopDeviceModel model) {
        // 调用修改方法
        IService.update(model);
        return ResultWrapper.getSuccessResultWrapperByMsg("修改门店设备成功");
    }


    /**
     * 门店设备 删除
     * @param id ID
     * @return ResultVo
     */
    @ApiOperation(value = "删除门店设备数据", notes = "删除门店设备数据")
    @PreAuthorize("hasAuthority('shop_device_delete')")
    @OperateLogger(description = "删除门店设备数据",
            module = ModuleEnum.MODULE_UNKNOWN, operationType = OperationTypeEnum.DELETE, db = true)
    @Override
    public ResultWrapper<?> del(String id){
        IService.delete(id);
        return ResultWrapper.getSuccessResultWrapperByMsg("删除门店设备成功");
    }

    /**
     * 门店设备 批量删除
     * @param ids ID 数组
     * @return ResultVo
     */
    @ApiOperation(value = "批量删除门店设备数据", notes = "批量删除门店设备数据")
    @PreAuthorize("hasAuthority('shop_device_delete')")
    @OperateLogger(description = "批量删除门店设备数据",
            module = ModuleEnum.MODULE_UNKNOWN, operationType = OperationTypeEnum.DELETE, db = true)
    @Override
    public ResultWrapper<?> delAll(String ids){
        String[] idArray = Convert.toStrArray(ids);
        IService.deleteAll(idArray);
        return ResultWrapper.getSuccessResultWrapperByMsg("批量删除门店设备成功");
    }

    /**
     * 门店设备 Excel 导出认证
     *
     * @param type 类型
     * @param request request
     */
    @ApiOperation(value = "Excel 导出认证", notes = "Excel 导出认证")
    @PreAuthorize("hasAnyAuthority('shop_device_export', 'shop_device_import')")
    @Override
    public ResultWrapper<String> exportExcelAuth(String type, HttpServletRequest request) {
        Optional<String> certificateOptional =
                super.excelExportAuth(type, SysShopDeviceRestApi.SUB_TITLE, request);
        if(!certificateOptional.isPresent()){
            return ResultWrapper.getErrorResultWrapper();
        }
        return ResultWrapper.getSuccessResultWrapper(certificateOptional.get());
    }


    /**
     * 门店设备 Excel 导出
     * @param response response
     */
    @ApiOperation(value = "导出Excel", notes = "导出Excel")
    @PreAuthorize("hasAuthority('shop_device_export')")
    @OperateLogger(description = "门店设备 导出Excel",
            module = ModuleEnum.MODULE_UNKNOWN, operationType = OperationTypeEnum.SELECT, db = true)
    @Override
    public void exportExcel(String certificate, HttpServletResponse response) {
        // 导出Excel
        super.excelExport(certificate, response);
    }

    /**
     * 门店设备 Excel 导入
     * 注：这里 RequiresPermissions 引入的是 Shiro原生鉴权注解
     * @param request 文件流 request
     * @return ResultVo
     */
    @ApiOperation(value = "导入Excel", notes = "导入Excel")
    @PreAuthorize("hasAuthority('shop_device_import')")
    @OperateLogger(description = "门店设备 Excel 导入",
            module = ModuleEnum.MODULE_UNKNOWN, operationType = OperationTypeEnum.INSERT, db = true)
    @Override
    public ResultWrapper<?> importExcel(MultipartHttpServletRequest request) {
        return super.importExcel(request);
    }

}